
package com.segment.dcore.base.filter;

import com.segment.dcore.base.constants.ServiceConstants;
import com.segment.dcore.base.service.KCoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 服务调用器
 *
 * Created by huapeng.hhp on 2017/2/27.
 */
public class ServiceFilterRegister implements KCoreService, FilterRegister {

	private static Map<String, ServiceFilterRegister> registers = new HashMap<>();
	// 根据消费者ID来注册对应的消费者
	static {
		registers.put(ServiceConstants.DUBBO_FILTER_REGISTER_SERVICE, new ServiceFilterRegister());
		registers.put(ServiceConstants.SERVLET_FILTER_REGISTER_SERVICE, new ServiceFilterRegister());
	}

	/** 根据消费者ID来获取对应的Consumer */
	public static ServiceFilterRegister getFilterRegisterService(String name) {
		return registers.get(name);
	}

	private static final Logger LOGGER = LoggerFactory.getLogger(ServiceFilterRegister.class);
	/** 拦截器列表 */
	private List<ServiceFilter> filterList = new ArrayList<>();

	@Override
	public void doService(InvokeContext invokeContext) {
		new FilterChain(filterList).doFilter(invokeContext);
	}

	@Override
	public void filterCreated(ServiceFilter serviceFilter) {
		// 防止过滤器重复加载
		for (ServiceFilter tmpFilter : filterList) {
			if (tmpFilter.getClass().getName().equals(serviceFilter.getClass().getName()))
				return;
		}
		LOGGER.info("添加过滤器：" + serviceFilter.getClass().getName());
		filterList.add(serviceFilter);
		// 对filter进行重新排序
		Collections.sort(filterList, new Comparator<ServiceFilter>() {
			public int compare(ServiceFilter objectSource, ServiceFilter objectTarget) {
				int sourceOrder = objectSource.getOrder();
				int targetOrder = objectTarget.getOrder();
				return sourceOrder - targetOrder;
			}
		});
	}

	@Override
	public void filterDestroied(ServiceFilter serviceFilter) {
		filterList.remove(serviceFilter);
	}
}
